#!/bin/sh
set -e

# 检查必要命令
command -v php >/dev/null 2>&1 || { echo >&2 "PHP not found"; exit 1; }

# 简单的端口检查函数
check_port() {
    hostport=$1
    timeout=${2:-30}
    end=$(( $(date +%s) + timeout ))
    
    host=$(echo "$hostport" | cut -d: -f1)
    port=$(echo "$hostport" | cut -d: -f2)
    
    echo "⏳ 等待服务: $host:$port"
    while [ $(date +%s) -lt $end ]; do
        if nc -z "$host" "$port" 2>/dev/null; then
            echo "✅ 服务就绪: $host:$port"
            return 0
        fi
        sleep 1
    done
    
    echo "❌ 等待服务超时: $host:$port"
    return 1
}

graceful_shutdown() {
    echo "🛑 收到终止信号，优雅停止服务..."
    if [ -f "/var/www/storage/swoole.pid" ]; then
        pid=$(cat "/var/www/storage/swoole.pid")
        if ps -p "$pid" >/dev/null 2>&1; then
            kill -TERM "$pid" 2>/dev/null && sleep 3
        fi
    fi
    exit 0
}

trap 'graceful_shutdown' TERM INT

# 等待依赖服务
if [ -n "$WAIT_FOR" ]; then
    check_port "$WAIT_FOR" 30
fi

# 设置工作目录
cd /var/www || exit 1

# 第一步：检查并安装 Composer 依赖
if [ -f "composer.json" ] && command -v composer >/dev/null 2>&1; then
    if [ ! -d "vendor" ] || [ "composer.lock" -nt "vendor" ]; then
        echo "📦 安装 Composer 依赖..."
        composer install --no-dev --optimize-autoloader --no-interaction --no-progress
        
        # 确保 vendor/autoload.php 存在
        if [ ! -f "vendor/autoload.php" ]; then
            echo "❌ vendor/autoload.php 未生成，尝试重新安装..."
            composer dump-autoload --optimize
        fi
    else
        echo "✅ Composer 依赖已是最新"
    fi
fi

# 第二步：验证自动加载文件是否存在
if [ ! -f "vendor/autoload.php" ]; then
    echo "❌ 错误: vendor/autoload.php 不存在"
    echo "请检查 Composer 依赖是否安装正确"
    exit 1
fi

# 第三步：验证 dotenv 包是否存在
if [ ! -d "vendor/vlucas/phpdotenv" ]; then
    echo "❌ 错误: vlucas/phpdotenv 包未安装"
    echo "尝试重新安装依赖..."
    composer require vlucas/phpdotenv ^5.6 --no-interaction --no-progress
fi

# 第四步：执行主命令
echo "🚀 启动应用服务..."
exec "$@" &

# 进程监控
background_pid=$!
while kill -0 "$background_pid" 2>/dev/null; do
    sleep 5
done

# 如果进程退出，检查退出状态
wait "$background_pid"
exit $?